package top.healthylife.service;/*
 *@Author GaoZeXi
 *@Created time 2020/4/18 6:25
 *@Description:
 * Step by Step  and Stand on,  You Are The Best Investment!!!
 */

import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import top.healthylife.domain.Permission;
import top.healthylife.domain.Role;
import top.healthylife.domain.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if (user==null) {
            return null;
        }
        //定义一个list集合,用来存储权限
        List<GrantedAuthority> list = new ArrayList<>();

        //动态给当前用户授权
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //遍历角色集合,给用户授予角色
            list.add(new SimpleGrantedAuthority((role.getKeyword())));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //遍历权限集合,为用户授权
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        org.springframework.security.core.userdetails.User securityUser =
                new org.springframework.security.core.userdetails.User(username,
                        user.getPassword(),list);
        return securityUser;
    }
}
